package com.pic.mgt.haishin.executer;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

import org.springframework.dao.DataAccessException;

import com.pic.mgt.dao.ITargetMessageDao;
import com.pic.mgt.dao.TargetMessageDao;
import com.pic.mgt.executer.IGXTypeExecutionException;
import com.pic.mgt.executer.MessageTypeExecutionException;
import com.pic.mgt.executer.MessageUnitExecuter;
import com.pic.mgt.haishin.unit.HaishinMessage;
import com.pic.mgt.unit.Message;


public abstract class HaishinMessageUnitExecuter
						extends MessageUnitExecuter {
	
	protected ITargetMessageDao targetMessageDao;

	@Override
	protected void executeMessageType() throws MessageTypeExecutionException {
		try {
			executeIGXType();
		} catch (IGXTypeExecutionException e) {
			throw new MessageTypeExecutionException("", e);
		}
	}
	
	protected void insertTargetMessage (HaishinMessage haishinMessage)
												throws DataAccessException {
		// 新增資料 (table: *_target_message)
		Map<String, Object> inserValuesMap = getInsertTargetMessageBasicValuesMap(haishinMessage);
		// throws DataAccessException
		this.targetMessageDao.insertBasic(inserValuesMap);
	}

	private Map<String, Object> getInsertTargetMessageBasicValuesMap(HaishinMessage haishinMessage) {
		Map<String ,Object> insertValuesMap = new HashMap<String, Object>();

		insertValuesMap.put(TargetMessageDao._confirmationFile, haishinMessage.getConfirmationFilename());
		insertValuesMap.put(TargetMessageDao._transactionFile, haishinMessage.getTransactionFilename());
		insertValuesMap.put(TargetMessageDao._transactionTime, new Timestamp(haishinMessage.getTransactionTime().getTime()));
		insertValuesMap.put(TargetMessageDao._unitName, haishinMessage.getUnitName());
		insertValuesMap.put(TargetMessageDao._terminalId, haishinMessage.getTerminalId());

		return insertValuesMap;
	}
	
	// (送多方新增)
	/**
	 * 更新 *_business_target_action table 內的最後交易時間。
	 * @param message
	 */
	protected void updateBusinessTargetActionTxTime(Message message) {
		// 更新資料 (table: *_business_target_action)
		this.businessTargetActionDao.updateLastTxTimeByFilename(
				new Timestamp(message.getTransactionTime().getTime()),
				message.getTransactionFilename());
	}
	
	protected abstract void executeIGXType()
								throws IGXTypeExecutionException;
	
	// --- getter and setter ---
	
	public void setTargetMessageDao(ITargetMessageDao targetMessageDao) {
		this.targetMessageDao = targetMessageDao;
	}
	
}
